'use client';

import { useEffect, useState } from 'react';
import ToolsBarSortMenu from './ToolsBarSortMenu';
import './ToolsBarMod.scss';
import { showLoading } from '@/components/ContentLoading';
import { postAddMySku } from '@/services';
import { showToast } from '@/components/Toast';

const ToolsBarMod = ({
  products,
  isLogin,
  onSelectChange,
  onAddMySkus,
  hide,
  onOpenFilter,
}: {
  products: Obj;
  isLogin: boolean;
  onSelectChange?: Fn;
  onAddMySkus?: Fn;
  hide?: boolean;
  onOpenFilter: Fn;
}) => {
  const { result, current_page, total_pages, page_size, total, hasError } =
    products;

  const handleSelectAll = () => {
    const newList = result?.map((sku: Obj) => ({ ...sku, my_sku: true }));
    onSelectChange && newList && onSelectChange(newList);
  };
  const handleUnSelectAll = () => {
    const newList = result?.map((sku: Obj) => ({ ...sku, my_sku: false }));
    onSelectChange && newList && onSelectChange(newList);
  };

  const handleAddToMySkuList = async () => {
    const selected = result
      ?.filter((sku: any) => sku.my_sku)
      ?.map((sku: any) => sku.sku);
    console.log('🌈🌈🌈Add My Sku List : ', selected);
    if (selected?.length) {
      const hideLoading = showLoading({
        inner: false,
        mask: true,
        maskStyle: { backgroundColor: 'rgba(255,255,255,.05)' },
      });
      const res = await postAddMySku({ skus: selected.join() }).catch(e => {
        void e;
      });
      console.log(res?.message);
      res &&
        showToast({
          type: res.success ? 'success' : 'error',
          message: res?.message,
          duration: 25000,
        });
      hideLoading();
    }
  };

  const handleFilterClick = () => {
    console.log('🌈🌈🌈click filter');
    onOpenFilter && onOpenFilter();
  };

  const [selectedList, setSelectedList] = useState<any[]>([]);
  useEffect(() => {
    const selected = result?.filter((sku: any) => sku.my_sku);
    selected && setSelectedList(selected);
  }, [result]);

  return (
    <div className="content-toolsbar">
      {hide || total == undefined ? (
        <></>
      ) : (
        <>
          <div className="toolsbar-left">
            {isLogin && (
              <button
                id="toolsbar_filter_button"
                className="toolsbar-filter-button"
                onClick={handleFilterClick}
              >
                <b className="iconfont icon-filter"></b>
                Filter
                <span className="iconfont icon-expand-line"></span>
              </button>
            )}
            {isLogin && <ToolsBarSortMenu />}
            {total !== undefined && (
              <span className="toolsbar-items">{total} items</span>
            )}
          </div>
          {isLogin && (
            <div className="toolsbar-right">
              <button
                className={
                  'toolsbar-button' +
                  (selectedList?.length != result?.length
                    ? ' toolsbar-button-activated'
                    : '')
                }
                onClick={handleSelectAll}
              >
                Select All
              </button>
              <button
                className={
                  'toolsbar-button' +
                  (selectedList?.length > 0 ? ' toolsbar-button-activated' : '')
                }
                onClick={handleUnSelectAll}
              >
                Unselect All
              </button>
              <button
                className={
                  'toolsbar-button button-dark' +
                  (selectedList?.length > 0 ? ' toolsbar-button-activated' : '')
                }
                onClick={handleAddToMySkuList}
              >
                Add to My SKU List
                <span className="iconfont icon-direction-right"></span>
              </button>
            </div>
          )}
        </>
      )}
    </div>
  );
};

export default ToolsBarMod;
